#include <libpq-fe.h>
#include <iostream>
#include <string>
#include "pgsql.h"
#include <chrono>
#include <fstream>
#include <vector>
#include "table.h"
#include "predicate.h"
#include "tuplesense.h"

using namespace std;

//database-config
const char* hostaddr = "localhost";
const char* port = "5432";
const char* dbname = "tpch01";
const char* user = "postgres";
const char* password = "";


time_t GetCurrentTimeMsec() {
	auto time = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now());
	time_t timestamp = time.time_since_epoch().count();
	return timestamp;
}


void Stringsplit(const string& str, const char split, vector<string>& res)
{
	if (str == "")		return;
	string strs = str + split;
	size_t pos = strs.find(split);

	while (pos != strs.npos)
	{
		string temp = strs.substr(0, pos);
		res.push_back(temp);
		strs = strs.substr(pos + 1, strs.size());
		pos = strs.find(split);
	}
}

PGconn* conn;

int main(int argc,char* argv[]) {
	
	time_t t_begin = GetCurrentTimeMsec();

	PGsql pgsql(hostaddr, port, dbname, user, password);
	
	conn = pgsql.getConn();

	string sql1 = "select l_shipmode,l_extendedprice from lineitem";
	vector<string> cols1 = { "l_shipmode","l_extendedprice"};
	Table t1;
	t1.input_data(conn,"lineitem", cols1,sql1);
	t1.add_tracebit();
	t1.save_todb(conn);
	//t1.table_print();

	string sql_temp = "select l_shipmode,sum( cast(l_extendedprice as float) ) \
						from lineitem_temp \
						 where lineitem_tbit = ";


	TupleSense tuplesense;
	tuplesense.conn = conn;
	tuplesense.all_tables.push_back(t1);
	tuplesense.sense_tables.push_back("lineitem");
	tuplesense.computeTupleSenseGroup(sql_temp,"l_shipmode");

	time_t t_end = GetCurrentTimeMsec();

	cout << "[Timecost] timecost : " << (t_end - t_begin) << endl;
	

	/*
	Table t_res;

	t_res.table_foreignkey_join(t1, "t1fk", t2, "t2mk", t_res);
	t_res.table_print();
	
	Table t_res2;
	t_res2.table_normal_join(t1, t2, t_res2);
	t_res2.table_print();

	Predicate pred;
	pred.allneed_cols.push_back("t1mk");
	pred.left_value.push_back("t1mk");
	pred.mid_op.push_back("=");
	pred.right_value.push_back("2");

	t_res.execute_where(pred);
	t_res.table_print();
	*/
	
}

